package dao

import (
	"album/model"
	"context"
	"errors"
	"github.com/zeromicro/go-zero/core/logx"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
)

type ProcessDao struct {
	db *mongo.Database
}

func (p *ProcessDao) FindProcess(ctx context.Context, userId, AlbumId int64, TrackId int64) (*model.Process, error) {
	pro := &model.Process{}
	filter := bson.D{{Key: "userId", Value: userId},
		{Key: "albumId", Value: AlbumId},
		{Key: "trackId", Value: TrackId}}
	err := p.db.Collection(pro.Table()).FindOne(ctx, filter).Decode(&pro)
	if err != nil && err != mongo.ErrNoDocuments {
		return nil, err
	}
	return pro, nil
}
func (p *ProcessDao) Update(ctx context.Context, userId, albumId int64, trackId int64, breakSecond float32) error {
	var pro model.Process
	filter := bson.D{bson.E{Key: "userId", Value: userId},
		{Key: "albumId", Value: albumId},
		{Key: "trackId", Value: trackId}}
	//update := bson.M{"$set": bson.M{
	//	"breakSecond": breakSecond,
	//}}
	col := p.db.Collection(pro.Table())
	//filter := col.FindOne(ctx, model.Process{UserId: userId, AlbumId: albumId, TrackId: trackId})
	//if findRes.Err() == mongo.ErrNoDocuments {
	//	// 这边查询不到
	//	fmt.Println(err)
	//}
	update := bson.D{bson.E{Key: "$set",
		Value: bson.E{Key: "breakSecond", Value: breakSecond}}}
	updateResult, err := col.UpdateOne(context.Background(), filter, update)
	if err != nil {
		log.Fatal(err)
	}
	if updateResult.MatchedCount > 0 && updateResult.ModifiedCount > 0 {
		return nil
	} else {
		logx.Error(errors.New("Document exists but was not modified"))
		return nil
	}
}
func (p *ProcessDao) Create(ctx context.Context, pro *model.Process) error {
	_, err := p.db.Collection(pro.Table()).InsertOne(ctx, &pro)
	if err != nil {
		return err
	}
	return nil
}
func (p *ProcessDao) FindProcessTo1(ctx context.Context, userId int64) (pro *model.Process, err error) {
	col := p.db.Collection(pro.Table())
	// 定义查询过滤器
	filter := bson.D{{Key: "userId", Value: userId}}
	// 定义排序选项，按 createdAt 字段降序排列
	sortOptions := options.FindOne().SetSort(bson.D{{Key: "createdAt", Value: -1}})
	err = col.FindOne(context.Background(), filter, sortOptions).Decode(&pro)
	if err != nil {
		return nil, err
	}
	return pro, nil
}
func NewProcessDao(db *mongo.Database) *ProcessDao {
	return &ProcessDao{
		db: db,
	}
}
